package com.example.dormitoryscoresystem.controller;

import com.example.dormitoryscoresystem.entity.ScoreRecord;
import com.example.dormitoryscoresystem.repository.ScoreRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@RestController
@RequestMapping("/api/monthlyRank")
public class MonthlyRankController {

    @Autowired
    private ScoreRepository scoreRepository;

    @GetMapping("/trend")
    public Map<String, Object> getMonthlyTrend(
            @RequestParam String dormId,
            @RequestParam String floor,
            @RequestParam int year,
            @RequestParam int month) {

        // 定义该月的起始时间和结束时间
        LocalDateTime startOfMonth = LocalDateTime.of(year, month, 1, 0, 0, 0, 0);
        LocalDateTime endOfMonth = startOfMonth.withDayOfMonth(startOfMonth.getMonth().length(startOfMonth.toLocalDate().isLeapYear()))
                .withHour(23)
                .withMinute(59)
                .withSecond(59)
                .withNano(999999999);

        // 查询指定寝室、楼层和时间范围内的评分记录
        List<ScoreRecord> records = scoreRepository.findByDormIdAndFloorAndCreatedTimeBetween(
                dormId,
                floor,
                startOfMonth,
                endOfMonth
        );

        // 格式化记录为指定格式: [{date, score}, ...]
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        List<Map<String, Object>> trendData = new ArrayList<>();
        for (ScoreRecord record : records) {
            Map<String, Object> trendEntry = new HashMap<>();
            trendEntry.put("date", record.getCreatedTime().format(formatter));  // 格式化日期
            trendEntry.put("score", record.getScore());  // 获取评分
            trendData.add(trendEntry);
        }

        // 构建并返回响应结果
        Map<String, Object> result = new HashMap<>();
        result.put("trend", trendData);
        return result;
    }
}
